package com.sandy.demo.auth

import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import org.springframework.web.filter.GenericFilterBean

import javax.servlet.FilterChain
import javax.servlet.ServletException
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@Slf4j
@CompileStatic
class RestLogoutFilter extends GenericFilterBean {

    String endpointUrl
    String headerName

    TokenStorageService tokenStorageService = new MemoryTokenStorageService()

    @Override
    void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        def req = request as HttpServletRequest
        def res = response as HttpServletResponse

        def actualUri =  req.requestURI - req.contextPath

        if (actualUri == endpointUrl) {

            //Only POST is supported
//            if (req.method != 'POST') {
//                log.debug "${req.method} HTTP method is not supported. Setting status to ${HttpServletResponse.SC_METHOD_NOT_ALLOWED}"
//                res.setStatus HttpServletResponse.SC_METHOD_NOT_ALLOWED
//                return
//            }

            def accessToken = findToken(req)

            if (accessToken) {
                log.debug "Token found: ${accessToken}"

                try {
                    log.debug "Trying to remove the token"
                    tokenStorageService.removeToken accessToken.accessToken
                } catch (TokenNotFoundException ignored) {
                    res.setStatus HttpServletResponse.SC_NOT_FOUND, "Token not found"
                }
            } else {
                log.debug "Token is missing. Sending a ${HttpServletResponse.SC_BAD_REQUEST} Bad Request response"
                res.setStatus HttpServletResponse.SC_BAD_REQUEST, "Token header is missing"
            }

        } else {
            chain.doFilter(request, response)
        }
    }

    AccessToken findToken(HttpServletRequest request) {
        def tokenValue = request.getParameter("token")
        return tokenValue ? new AccessToken(tokenValue) : null
    }
}
